package cn.stephen.study.demoproject.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.stephen.study.demoproject.dao.dbone.ReportMapper;
import cn.stephen.study.demoproject.dao.dbtwo.StationEquipmentMapper;
import cn.stephen.study.demoproject.entity.*;
import cn.stephen.study.demoproject.service.SBJCYJService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import freemarker.template.Version;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
//import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;

@Component
public class WordUtil {
    private Configuration configuration = null;
    @Autowired
    private SBJCYJService sbjcyjService;
    @Autowired
    private StationEquipmentMapper stationEquipmentMapper;

    @Autowired
    private ReportMapper reportMapper;

    public WordUtil() {
        Configuration configuration = new Configuration(new Version("2.3.0"));
        configuration.setDefaultEncoding("UTF-8");
    }

    private static WordUtil utils;

    @PostConstruct
    public void init() {
        utils = this;
        utils.sbjcyjService = this.sbjcyjService;
        utils.stationEquipmentMapper = this.stationEquipmentMapper;
        utils.reportMapper = this.reportMapper;
    }

    public static void test(Integer type, String uniqure_code, Integer equipmentType) {
        utils.sbjcyjService.getValue(type, uniqure_code, equipmentType);
        utils.sbjcyjService.findAlls(null, type, null, null, null);
    }


    /**
     * 将文本信息转为word输出
     *
     * @param
     * @throws Exception
     */
    public File createDoc(String stationCode, Integer type, String fileName) {
        Map<String, Object> dataMap = new HashMap<>();
        Template t = null;
        Report report = new Report();
        report.setId(UUID.randomUUID().toString());
        report.setStationCode(stationCode);
        report.setTime(new Date());
        report.setPath(fileName+ ".doc");
        report.setType(String.valueOf(type));
        fileName = "D:\\tool\\baobiao\\" + fileName + ".doc";
        File file = new File(fileName);
        try {
            getAllDate(dataMap, stationCode, type);
            Configuration configuration = new Configuration(new Version("2.3.0"));
            configuration.setDefaultEncoding("UTF-8");
            //        configuration.setClassForTemplateLoading(this.getClass(), "D:/"); //模板文件所在路径
            configuration.setDirectoryForTemplateLoading(new File("D:\\tool\\baobiao"));
            t = configuration.getTemplate("moban.ftl"); //获取模板文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            t.process(dataMap, out);  //将填充数据填入模板文件并输出到目标文件
            out.close();
            //保存记录到数据库
            Report path = utils.reportMapper.findByFileName(report.getPath());
            if(path==null) {
                utils.reportMapper.insetReport(report);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }

        return file;
    }

    /**
     * 导出word 并提供下载
     *
     * @param response
     */
    public void download(HttpServletResponse response, String stationCode, Integer type) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File file = createDoc(stationCode, type, "aaaa");
            response.setContentType("application/msword;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=\""
                    + new String(file.getName().getBytes(), "iso-8859-1") + "\"");

            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[10240];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获得图片的base64编码
    private String getBase64(String imgUrl) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        URL url = null;
        InputStream in = null;
        HttpURLConnection httpUrl = null;
        byte[] by = new byte[1024];

        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            in = httpUrl.getInputStream();
            int len = -1;
            while ((len = in.read(by)) != -1) {
                data.write(by, 0, len);
            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(data.toByteArray());
        return Base64.encodeBase64String(data.toByteArray());
    }

    //获取数据
    private void getAllDate(Map<String, Object> dataMap, String stationCode, Integer type) {
        //获取所有设备信息
        List<Map<String, String>> all1 = utils.stationEquipmentMapper.findAll1(stationCode, null, null);
        List<String> uniqure_codes = new ArrayList<>();
        List<String> uniqure_codes1 = new ArrayList<>();
        List<String> uniqure_codes2 = new ArrayList<>();
        for (Map<String, String> map : all1) {
            if(map.get("EQUIPMENTTYPE")!=null){
                if (map.get("EQUIPMENTTYPE").equals("204")) {
                    uniqure_codes.add(map.get("JSCJ204A050"));//gnss
                } else if (map.get("EQUIPMENTTYPE").equals("212")) {
                    uniqure_codes1.add(map.get("JSCJ204A050"));//深部位移
                } else if (map.get("EQUIPMENTTYPE").equals("214")||map.get("EQUIPMENTTYPE").equals("214,888")) {
                    uniqure_codes2.add(map.get("JSCJ204A050"));//地下水位
                }
            }
        }
        dataMap.put("allNum", all1 == null ? 0 : all1.size());//传感器得数量
        dataMap.put("allNumUse", "100%");//传感器使用率
        String time1 = "";//监测时间
        String type1="";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年M月d日");
        if (type == 1) {
            //周报表，获取上周数据
            Date beginDayOfWeek = TimeUtil.getBeginDayOfLastWeek();
            Date endDayOfWeek = TimeUtil.getEndDayOfLastWeek1();
            time1 = dateFormat.format(beginDayOfWeek) + "~" + dateFormat.format(endDayOfWeek);
            type1="周";
        } else {
            //月报表 ，获取月数据
            Date beginDayOfMonth = TimeUtil.getBeginDayOfLastMonth();
            Date endDayOfMonth = TimeUtil.getEndDayOfLastMonth();
            time1 = dateFormat.format(beginDayOfMonth) + "~" + dateFormat.format(endDayOfMonth);
            type1="月";
        }
        dataMap.put("time1", time1);//传感器使用率
        String time2 = TimeUtil.getNowTime_CN_yMdH();//获取报告时间
        dataMap.put("type", type1);//类别
        dataMap.put("time2", time2);//传感器使用率
        getData(dataMap, type, uniqure_codes, 204);
        getData1(dataMap, type, uniqure_codes1, 212);
        getData2(dataMap, type, uniqure_codes2, 214);
        getData3(dataMap, type);
    }

    public void getList(List<List<String>> list1){
        List<String> list=new ArrayList<>();
        for (int i=0;i<9;i++){
            String a=null;
            list.add(a);
        }
        list1.add(list);
    }

    //获取GNSS数据
    private void getData(Map<String, Object> dataMap, Integer type, List<String> uniqure_codes, Integer equipmentType) {
//        String value = utils.sbjcyjService.getValue(1, "01010100135", 0);
        List<Value> ValueListAll = new ArrayList<>();
        for (String uniqure_code : uniqure_codes) {
            String value = utils.sbjcyjService.getValue(type, uniqure_code, equipmentType);
            JSONObject jo = JSONObject.parseObject(value, Feature.IgnoreNotMatch, Feature.IgnoreNotMatch);//不忽略null 保持顺序
            String data = String.valueOf(jo.get("data"));
            List<List<String>> list1 = (List<List<String>>) JSONArray.parse(data);
            if(list1!=null){
                if(list1.size()>20){
                    list1 = PageUtil.listPaging(list1, 1, 20);//取前20条数据
                }
                List<Value> ValueList = new ArrayList<>();
                for (List<String> values : list1) {
                    Value value1 = new Value();
                    if (values.size() > 0) {
                        value1.setValue1(values.get(0) == null ? " " : String.valueOf(values.get(0)));
                        value1.setValue2(values.get(1) == null ? " " : String.valueOf(values.get(1)));
                        value1.setValue3(values.get(2) == null ? " " : String.valueOf(values.get(2)));
                        value1.setValue4(values.get(3) == null ? " " : String.valueOf(values.get(3)));
                        value1.setValue5(values.get(4) == null ? "" : String.valueOf(values.get(4)));
                        value1.setValue6(values.get(6) == null ? " " : String.valueOf(values.get(6)));
                        value1.setValue7(values.get(7) == null ? " " : String.valueOf(values.get(7)));
                        value1.setValue8(values.get(8) == null ? " " : String.valueOf(values.get(8)));
                        value1.setValue9(values.get(9) == null ? " " : String.valueOf(values.get(9)));
                        ValueList.add(value1);
                    }
                }
                ValueListAll.addAll(ValueList);
            }
        }

        dataMap.put("ValueList", ValueListAll);
    }

    //获取深部位移数据
    private void getData1(Map<String, Object> dataMap, Integer type, List<String> uniqure_codes, Integer equipmentType) {
//        String value = utils.sbjcyjService.getValue(1, "01020700004", 2);
        List<Value> ValueListAll = new ArrayList<>();
        for (String uniqure_code : uniqure_codes) {
            String value = utils.sbjcyjService.getValue(type, uniqure_code, equipmentType);
            JSONObject jo = JSONObject.parseObject(value, Feature.IgnoreNotMatch, Feature.IgnoreNotMatch);//不忽略null 保持顺序
            String data = String.valueOf(jo.get("data"));
            List<List<String>> list1 = (List<List<String>>) JSONArray.parse(data);
            if(list1!=null){
                if(list1.size()>20){
                    list1 = PageUtil.listPaging(list1, 1, 20);//取前20条数据
                }
                List<Value> ValueList = new ArrayList<>();
                for (List<String> values : list1) {
                    Value value1 = new Value();
                    if (values.size() > 0) {
                        value1.setValue1(values.get(0) == null ? " " : String.valueOf(values.get(0)));
                        value1.setValue2(values.get(1) == null ? " " : String.valueOf(values.get(1)));
                        value1.setValue3(values.get(2) == null ? " " : String.valueOf(values.get(2)));
                        value1.setValue4(values.get(3) == null ? " " : String.valueOf(values.get(3)));
                        value1.setValue5(values.get(4) == null ? "" : String.valueOf(values.get(4)));
                        value1.setValue6(values.get(5) == null ? " " : String.valueOf(values.get(5)));
                        value1.setValue7(values.get(6) == null ? " " : String.valueOf(values.get(6)));
                        value1.setValue8(values.get(7) == null ? " " : String.valueOf(values.get(7)));
                        ValueList.add(value1);
                    }
                }
                ValueListAll.addAll(ValueList);
            }
        }

        dataMap.put("ValueList1", ValueListAll);
    }

    //获取低下水位数据
    private void getData2(Map<String, Object> dataMap, Integer type, List<String> uniqure_codes, Integer equipmentType) {
//        String value = utils.sbjcyjService.getValue(1, "05162300069", 3);
        List<Value> ValueListAll = new ArrayList<>();
        for (String uniqure_code : uniqure_codes) {
            String value = utils.sbjcyjService.getValue(type, uniqure_code, equipmentType);
            JSONObject jo = JSONObject.parseObject(value, Feature.IgnoreNotMatch, Feature.IgnoreNotMatch);//不忽略null 保持顺序
            String data = String.valueOf(jo.get("data"));
            List<List<String>> list1 = (List<List<String>>) JSONArray.parse(data);
            if(list1!=null){
                if(list1.size()>20){
                    list1 = PageUtil.listPaging(list1, 1, 20);//取前20条数据
                }
                List<Value> ValueList = new ArrayList<>();
                for (List<String> values : list1) {
                    Value value1 = new Value();
                    if (values.size() > 0) {
                        value1.setValue1(values.get(0) == null ? " " : String.valueOf(values.get(0)));
                        value1.setValue2(values.get(1) == null ? " " : String.valueOf(values.get(1)));
                        value1.setValue3(values.get(2) == null ? " " : String.valueOf(values.get(2)));
                        value1.setValue4(values.get(3) == null ? " " : String.valueOf(values.get(3)));
                        value1.setValue5(values.get(4) == null ? "" : String.valueOf(values.get(4)));
                        value1.setValue6(values.get(5) == null ? " " : String.valueOf(values.get(5)));
                        value1.setValue7(values.get(6) == null ? " " : String.valueOf(values.get(6)));
                        ValueList.add(value1);
                    }
                }
                ValueListAll.addAll(ValueList);
            }
        }
        dataMap.put("ValueList2", ValueListAll);
    }

    //获取告警数据
    private void getData3(Map<String, Object> dataMap, Integer type) {
        System.out.println("444");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = "";
        String endTime = "";
        if (type == 1) {
            //周报表，获取上周数据
            Date beginDayOfWeek = TimeUtil.getBeginDayOfLastWeek();
            Date endDayOfWeek = TimeUtil.getEndDayOfLastWeek();
            startTime = sdf.format(beginDayOfWeek);
            endTime = sdf.format(endDayOfWeek);
        } else {
            //月报表 ，获取月数据
            Date beginDayOfMonth = TimeUtil.getBeginDayOfLastMonth();
            Date endDayOfMonth = TimeUtil.getEndDayOfLastMonth();
            startTime = sdf.format(beginDayOfMonth);
            endTime = sdf.format(endDayOfMonth);
        }
        List<SBJCYJ> sbjcyjs = utils.sbjcyjService.findAlls("", 5, startTime, endTime, null);
        //获取告警级别相关数据
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        int num4 = 0;
        for (SBJCYJ sbjcyj : sbjcyjs) {
            if (sbjcyj.getSBJCYJ050() == 1) {
                num1++;
            } else if (sbjcyj.getSBJCYJ050() == 2) {
                num2++;
            } else if (sbjcyj.getSBJCYJ050() == 3) {
                num3++;
            } else if (sbjcyj.getSBJCYJ050() == 4) {
                num4++;
            }
        }
        List<Value> ValueList = new ArrayList<>();
        if(sbjcyjs!=null){
            if(sbjcyjs.size()>20){
                sbjcyjs = PageUtil.listPaging(sbjcyjs, 1, 20);//取前20条数据
            }
            for (SBJCYJ values : sbjcyjs) {
                Value value1 = new Value();
                value1.setValue1(values.getSBJCYJ010() == null ? " " : values.getSBJCYJ010());
                value1.setValue2(values.getSBJCYJ020() == null ? " " : values.getSBJCYJ020());
                value1.setValue3(values.getSBJCYJ030() == null ? " " : String.valueOf(values.getSBJCYJ030()));
                value1.setValue4(values.getSBJCYJ040() == null ? " " : values.getSBJCYJ040());
                value1.setValue5(values.getSBJCYJ050() == null ? " " : String.valueOf(values.getSBJCYJ050()));
                value1.setValue6(values.getSBJCYJ060() == null ? " " : sdf.format(values.getSBJCYJ060()));
                value1.setValue7(values.getSBJCYJ070() == null ? " " : values.getSBJCYJ070());
                value1.setValue8(values.getSBJCYJ080() == null ? " " : values.getSBJCYJ080());
                value1.setValue9(values.getSBJCYJ090() == null ? " " : values.getSBJCYJ090());
                value1.setValue10(values.getSBJCYJ100() == null ? " " : values.getSBJCYJ100());
                value1.setValue11(values.getSBJCYJ110() == null ? " " : values.getSBJCYJ110());
                value1.setValue12(values.getSBJCYJ120() == null ? " " : String.valueOf(values.getSBJCYJ120()));
                ValueList.add(value1);
            }
        }
        dataMap.put("ValueList3", ValueList);
        dataMap.put("num1", num1);
        dataMap.put("num2", num2);
        dataMap.put("num3", num3);
        dataMap.put("num4", num4);
        dataMap.put("exception", num1 > 0 ? "异常" : "正常");

    }

    public void exportListWord() throws Exception {
        //构造数据
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<TestEntity> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            TestEntity testEntity = new TestEntity();
            testEntity.setId(i + 1);
            testEntity.setFirstName("firstName" + (i + 1));
            testEntity.setLastName("lastName" + (i + 1));
            testEntity.setMagicId("magicId" + (i + 1));
            list.add(testEntity);
        }
        dataMap.put("TestEntityList", list);
        dataMap.put("title", "ceshi");
        Configuration configuration = new Configuration(new Version("2.3.0"));
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(new File("D:\\tool"));
        File outFile = new File("D:\\test.doc");
        Template t = configuration.getTemplate("aaa.ftl", "utf-8");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
        t.process(dataMap, out);
        out.close();
    }

//    public  void createNewWord() {
//        ActiveXComponent _app = new ActiveXComponent("Word.Application");
//        _app.setProperty("Visible", Variant.VT_FALSE);
//        Dispatch documents = _app.getProperty("Documents").toDispatch();
//        // 打开FreeMarker生成的Word文档
//        Dispatch doc = Dispatch.call(documents, "Open", "test.doc", Variant.VT_FALSE, Variant.VT_TRUE).toDispatch();
//        // 另存为新的Word文档
//        Dispatch.call(doc, "SaveAs", "test.doc", Variant.VT_FALSE, Variant.VT_TRUE);
//
//        Dispatch.call(doc, "Close", Variant.VT_FALSE);
////        _app.invoke("Quit", new Variant[]{});
//        ComThread.Release();
//    }
}

